package com.example.video.file_server.common.config;

import io.minio.MinioClient;
import io.minio.errors.*;
import io.minio.policy.PolicyType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 *  Minio连接配置
 * <p/>
 *
 * @author : yj
 */
@Configuration
@Slf4j
public class MinioConfig {

@Autowired
private MinioConfigParams minioConfigParams;


    @Bean
    public MinioClient init()throws NoSuchAlgorithmException, IOException, InvalidKeyException, XmlPullParserException {
        try {
            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = new MinioClient(minioConfigParams.getEndpoint(), minioConfigParams.getAccessKey(), minioConfigParams.getSecretKey());
            // 检查存储桶是否已经存在
            boolean isExistImg = minioClient.bucketExists(minioConfigParams.getImgBucket());
            boolean isExistVideo = minioClient.bucketExists(minioConfigParams.getVideoBucket());
            boolean temporaryStorage = minioClient.bucketExists(minioConfigParams.getTemporaryStorage());
            if(isExistImg && isExistVideo && temporaryStorage) {
                log.info("Bucket already exists.");
            } else {
                if(!isExistImg){
                    minioClient.makeBucket(minioConfigParams.getImgBucket());
                    minioClient.setBucketPolicy(minioConfigParams.getImgBucket(),minioConfigParams.getReadOnlyPrefix(),PolicyType.READ_WRITE);
                    log.info("make bucket. { }",minioConfigParams.getImgBucket());
                }
                if(!isExistVideo){
                    minioClient.makeBucket(minioConfigParams.getVideoBucket());
                    minioClient.setBucketPolicy(minioConfigParams.getVideoBucket(),minioConfigParams.getReadOnlyPrefix(),PolicyType.READ_ONLY);
                    log.info("make bucket. { }",minioConfigParams.getVideoBucket());
                }
                if(!temporaryStorage){
                    minioClient.makeBucket(minioConfigParams.getTemporaryStorage());
                    minioClient.setBucketPolicy(minioConfigParams.getTemporaryStorage(),minioConfigParams.getReadOnlyPrefix(),PolicyType.READ_ONLY);
                    log.info("make bucket. { }",minioConfigParams.getTemporaryStorage());
                }
            }
            return minioClient;
        } catch(MinioException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return null;
    }

}
